<template>
<div class="container">
    <el-row>
        <el-col :span="1" style="text-align:center;    display:table;">
            <p class="md-text1">标题:</p>
        </el-col>
        <el-col :span="3">
            <el-input placeholder="标题" v-model="title"></el-input>
        </el-col>
        <el-col :span="1" style="text-align:center;    display:table;">
            <p style="font-size:15px; margin-top:8px;">分类:</p>
        </el-col>
        <el-col :span="3" style="margin-left: 20px">
            <el-select v-model="currentGroup" placeholder="选择分组" @change="OnChangeGroup">
                <el-option v-for="item in this.docgroups" :key="item.Int" :label="item.Name" :value="item.Int"></el-option>
            </el-select>
        </el-col>
        <el-col :span="3" style="margin-left:5px;">
            <el-select v-model="docType" placeholder="请选择" :value-key="docKey" @change="OnChangeType">
                <el-option v-for="item in this.doc_types" :key="item.id" :label="item.type_name" :value="item.id">
                </el-option>
            </el-select>
        </el-col>
        <el-col :span="1" style="text-align:center;  display:table; margin-top: 10px;margin-left:20px; font-size: 15px;">
            <el-checkbox v-model="is_public" style="color: white">不公开</el-checkbox>
        </el-col>
        <el-col :span="1" style="text-align:center;  display:table;margin-left:20px; font-size: 15px;">
            <el-button  @click="this.addTemplate">添加模板</el-button>
        </el-col>
        <el-col :span="3" style="margin-left:5px;">
            <el-select v-model="selectTemplate" placeholder="请选择" :value-key="docKey" @change="OnChangeType">
                <el-option v-for="item in this.templates" :key="item.id" :label="item.name" :value="item.id">
                </el-option>
            </el-select>
        </el-col>        
    </el-row>
    <el-row style="margin-top:30px;">
        <mavon-editor v-proportion="0.5" style="height: 700px" v-model="content" ref="md" @imgAdd="$imgAdd" @imgAddOrigin="$imgAddOrigin" />
    </el-row>
    <el-row>
        <el-col :span="24" style="margin-top: 20px">
            <el-button @click="addArticle">{{btnSave}}</el-button>
        </el-col>
    </el-row>
</div>
</template>

<script>
import axios from "@/api/ajax.js";
import Const from "@/const.js";
import Message from "element-ui/lib/message"
import Cookie from 'js-cookie'

export default {
    name: "editor",
    components: {},
    data: () => {
        return {
            currentGroup: "",
            docgroups: [],
            userInfo: {},
            content: "",
            title: "",
            btnSave: "提交",
            anchorAttrs: {
                target: "_blank",
                rel: "noopener noreferrer nofollow"
            },
            docGroupKey: "0",
            docKey: 1,
            docType: 0,
            doc_types: [],
            is_public: false,
            templates : [],
            selectTemplate:{},
        };
    },
    methods: {
    $imgAddOrigin(pos, $file) {
        console.log("$imgAddOrigin")
        // 第一步.将图片上传到服务器.
        var formdata = new FormData();
        formdata.append('image', $file);
        axios({
            url: (process.env.NODE_ENV === 'development' ? 'http://127.0.0.1:4596/api/image_upload_origin?type=' : 'https://www.testingcloud.club/sapi/api/image_upload_origin?type=') + $file.type.substring(6,) ,
            method: 'post',
            data: formdata,
            headers: {
                'Content-Type': 'multipart/form-data'
            },
        }).then((url) => {
            var url1 = (process.env.NODE_ENV === 'development' ? 'http://127.0.0.1:4596/api/image_download/' : 'https://www.testingcloud.club/sapi/api/image_download/') + url.data.url;
            // 第二步.将返回的url替换到文本原位置![...](0) -> ![...](url)
            /**
                * $vm 指为mavonEditor实例，可以通过如下两种方式获取
                * 1. 通过引入对象获取: `import {mavonEditor} from ...` 等方式引入后，`$vm`为`mavonEditor`
                * 2. 通过$refs获取: html声明ref : `<mavon-editor ref=md ></mavon-editor>，`$vm`为 `this.$refs.md`
                */

            this.$refs.md.$img2Url(pos, url1);
        })},
        // 绑定@imgAdd event
        $imgAdd(pos, $file) {
            // 第一步.将图片上传到服务器.
            var formdata = new FormData();
            formdata.append('image', $file);
            axios({
                url: (process.env.NODE_ENV === 'development' ? 'http://127.0.0.1:4596/api/image_upload?type=' : 'https://www.testingcloud.club/sapi/api/image_upload?type=') + $file.type.substring(6,) ,
                method: 'post',
                data: formdata,
                headers: {
                    'Content-Type': 'multipart/form-data'
                },
            }).then((url) => {
                var url1 = (process.env.NODE_ENV === 'development' ? 'http://127.0.0.1:4596/api/image_download/' : 'https://www.testingcloud.club/sapi/api/image_download/') + url.data.url;
                // 第二步.将返回的url替换到文本原位置![...](0) -> ![...](url)
                /**
                 * $vm 指为mavonEditor实例，可以通过如下两种方式获取
                 * 1. 通过引入对象获取: `import {mavonEditor} from ...` 等方式引入后，`$vm`为`mavonEditor`
                 * 2. 通过$refs获取: html声明ref : `<mavon-editor ref=md ></mavon-editor>，`$vm`为 `this.$refs.md`
                 */

                this.$refs.md.$img2Url(pos, url1);
            })
        },
        getAllTypes() {
            axios.get("doc_types", {
                withCredentials: true
            }).then(
                resp => {
                    this.doc_types = resp.data.Data;
                }
            ).catch(
                reason => {
                    Message.error(reason)
                }
            )
        },
        getGroupType(id) {
            axios.post("/group_type", {
                    id: id,
                })
                .then(response => {
                    if (response.data.Status === 0) {
                        this.doc_types = response.data.Data;
                        this.docType = this.doc_types[0].id;

                    }
                })
                .catch(reason => {
                    Message.error("网络错误:" + reason);
                });
        },
        OnChangeGroup() {
            this.getGroupType(this.docgroups[this.currentGroup].Int);
        },
        OnChangeType() {
            console.log(Number(this.docType))
        },
        addArticle() {
            if (this.btnSave === '提交') {
                axios.put("/article", {
                        title: this.title,
                        content: this.content,
                        type: Number(this.docType),
                        author: "admin",
                        is_public: this.is_public ? 1 : 0,
                    })
                    .then(response => {
                        if (response.data.Status === 0) {
                            Message.success("新增文章成功");
                        }
                    })
                    .catch(reason => {
                        Message.error("网络错误:" + reason);
                    });
            } else if(this.btnSave === '更新'){
                    axios.post("/article_update", {
                        title: this.title,
                        content: this.content,
                        author: "shit",
                        type: this.docType,
                        id:  Number(this.$route.query['id']),
                        is_public: this.is_public ? 1 : 0,
                    }).then(response => {
                        if (response.data.Status === 0) {
                            Message.success("更新文章成功");
                        }
                    }).catch(reason => {
                        Message.error("网络错误:" + reason);
                    });
            }
        },
        getDocGroup() {
            axios.get('/doc_groups', {}).then(response => {
                if (response.data.Status === 0) {
                    this.docgroups = response.data.Data;
                } else {}
            }).catch(reason => {
                Message.error("网络错误:" + reason);
            })

        },
        addTemplate(){
            console.log("add template",this.selectTemplate)
             this.getSingleTemplate()
            console.log("shit")
        },
        getTemplate(){
            axios.post('/get_doc_template?limit=' + this.limit + '&offset='  + this.offset ,{
                "title":"",
            }).then(response=> {
                        this.templates = [];
                        if (response.data.Status === 0)
                        {   
                            this.templates = response.data.Data
                        }
                    }
                ).catch(reason => {
                    Message.error("网络错误:" + reason);
            });
        },
        getSingleTemplate(id){
            axios.get('/doc_template/' + this.selectTemplate).then(response=> {
                        if (response.data.Status === 0)
                        {   
                            this.content += response.data.Data.content
                        }
                    }
                ).catch(reason => {
                    Message.error("网络错误:" + reason);
            });
        }
    },
    created() {
        this.getTemplate()
        this.getDocGroup();
        if (this.$route.query['id'] !== undefined) {
            // 如果有query说明是旧的文档编辑
            //todo 通过接口获取旧的文档，添加到新的文档里面去。
            let url = '/article/' + this.$route.query['id'];
            axios.get(url, {
                withCredentials: true
            }).then(
                resp => {
                    this.docType = resp.data.Data.type;
                    this.title = resp.data.Data.title;
                    this.author = resp.data.Data.author;
                    this.content = resp.data.Data.content;
                    this.btnSave = '更新';
                    if (resp.data.Data.is_public == 1) {
                        this.is_public = true;
                    } else {
                        this.is_public = false;
                    }
                }
            ).catch(
                reason => {
                    Message.error(reason)
                }
            )
        }
        this.userInfo = JSON.parse(Cookie.get(Const.KEY_USER_INFO));
    },
    beforeCreate() {
        axios.get("doc_types", {
            withCredentials: true
        }).then(
            resp => {
                this.doc_types = resp.data.Data;
            }
        ).catch(
            reason => {
                Message.error(reason)
            }
        )
    }
};
</script>

<style>
.container {
    width: 100%;
}

.md-text {
    font-size: 12px;
    width: 100%;
}

.md-body {
    width: 100%;
    margin-left: 20px;
}

.md-text1 {
    font-size: 15px;
    margin-top: 10px;
}

.mavonEditor {
    width: 100%;
    height: 800px;
}
</style>
